package org.example;

import org.json.JSONArray;
import org.json.JSONException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;



public class PointInPolygon {
    // 判断点是否在多边形内的函数
    public static boolean isPointInPolygon(Point p, List<Point> polygon) {
        int intersections = 0;
        int n = polygon.size();
        for (int i = 0; i < n; i++) {
            Point p1 = polygon.get(i);
            Point p2 = polygon.get((i + 1) % n);
            // 检查点是否在边的 y 范围之间
            if ((p.y > Math.min(p1.y, p2.y)) && (p.y <= Math.max(p1.y, p2.y))) {
                // 计算射线与边的交点的 x 坐标
                double xIntersect = (p.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x;
                // 如果交点在点的右侧
                if (p.x < xIntersect) {
                    intersections++;
                }
            }
        }
        System.out.println(intersections);
        // 如果相交次数为奇数，点在多边形内
        return (intersections % 2 == 1);
    }

    // 从文件中读取多边形顶点的函数
    public static List<Point> readPolygonFromFile(String filename) throws IOException {
        List<Point> polygon = new ArrayList<>();
        try (FileReader fileReader = new FileReader(filename)) {
            StringBuilder stringBuilder = new StringBuilder();
            int character;
            while ((character = fileReader.read())!= -1) {
                stringBuilder.append((char) character);
            }
            String jsonString = stringBuilder.toString();
            JSONArray jsonArray = new JSONArray(jsonString);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONArray pointArray = jsonArray.getJSONArray(i);
                double x = pointArray.getDouble(0);
                double y = pointArray.getDouble(1);
                polygon.add(new Point(x, y));
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }

        // 打印读取到的多边形顶点
        for (Point p : polygon) {
            System.out.println("x: " + p.x + ", y: " + p.y);
        }
        return polygon;
    }

    public static void main(String[] args) {
        List<Point> pointsToTest = new ArrayList<>();
        pointsToTest.add(new Point(119.037089, 32.259867));
        pointsToTest.add(new Point(118.721489, 32.017388));
        pointsToTest.add(new Point(118.80657099, 32.0353893));
        pointsToTest.add(new Point(118.804173, 32.077862));
        try {
            List<Point> polygon = readPolygonFromFile("latlon.json");
            for (Point p : pointsToTest) {
                if (isPointInPolygon(p, polygon)) {
                    System.out.println(p.x + ", " + p.y + " is inside the polygon.");
                } else {
                    System.out.println(p.x + ", " + p.y + " is outside the polygon.");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}